const express = require('express')
const { expressjwt } = require('express-jwt')
const cors = require('cors')
const session = require('express-session')
const userRouter = require('./src/routers/user')
const adminRouter = require('./src/routers/admin')
const logTime = require('./src/middleware/logtime')
const logIndex = require('./src/middleware/logindex')
const logUser = require('./src/middleware/loguser')
const bodyParser = require('./src/middleware/bodyparser')
const { secretKey } = require('./src/constant')
const result = require('./src/middleware/result')

const app = express()

//注意jsonp 只支持get请求 ajax的dataType提供jsonp选项
app.get('/jsonp', (req, res) => {
  const funName = req.query.callback
  const data = { name: 'zs', age: 20 }
  const resStr = `${funName}(${JSON.stringify(data)})`
  res.send(resStr)
})

// 跨域中间件
app.use(cors())

//三个内置中间件
app.use(express.static('./public'))
app.use(express.json())

//引入session中间件
app.use(
  session({
    secret: 'hello session',
    resave: false,
    saveUninitialized: true
  })
)

//jwt中间件 requestProperty 默认值 auth
app.use(
  expressjwt({ secret: secretKey, algorithms: ['HS256'], requestProperty: 'user' }).unless({
    path: [/\/api\//, '/jsonp', '/']
  })
)

app.use(result)
//app.use(express.urlencoded({ extended: false }))
//自定义中间件 代替 express.urlencoded({ extended: false })
app.use(bodyParser)
//添加前缀
app.use('assets', express.static('./assets'))
//添加全局中间件 （注意：一定要放在路由前面 否则部分路由不生效）
app.use(logTime)
//添加路由模块 和 路由模块的中间件
app.use('/api', logUser, userRouter)
app.use('/admin', adminRouter)

app.get('/', logIndex, (req, res) => {
  throw new Error('奔溃不奔溃')
})

//错误级别的中间件 （注意：一定要放在路由后面 否则部分路由不生效）
app.use((err, req, res, next) => {
  if (err.name == 'UnauthorizedError') {
    res.send({ status: '401', msg: '权限不足' })
  }

  console.log('全局异常捕获 错误信息:', err.message)
  res.send('服务器发生了错误')
})

app.listen(80, () => {
  console.log('express server running on 127.0.0.1')
})
